import copy
import json
import time
import struct
import random
from paho.mqtt import client as mqtt_client

# 测试，使用的是 cabinet 模板的用户名密码
broker = 'afubzfb.iot.gz.baidubce.com'
port = 1883
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = "thingidp@afubzfb|test_cabinet|0|MD5"
password = "0f59bf40622ba73521152222134285b2"


def bytes_to_float(h1, h2, h3, h4):
    ba = bytearray()
    ba.append(h1)
    ba.append(h2)
    ba.append(h3)
    ba.append(h4)
    return struct.unpack("!f", ba)[0]


def float_to_bytes(f):
    bs = struct.pack("f", f)
    return (bs[3], bs[2], bs[1], bs[0])


def print_hex(bytes):
    l = [hex(int(i)) for i in bytes]
    print(" ".join(l))


def isequal_bytes(bytes1, bytes2):
    return True


def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    # Set Connecting Client ID
    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.will_set(topic="cabinet/offline", payload=r'emulator_json, offline', qos=0, retain=True)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def publish_test(client, topic):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"messages: {msg_count}"
        result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")
        msg_count += 1


def subscribe(client: mqtt_client, topic, on_message):
    client.subscribe(topic)
    client.on_message = on_message


def on_message_received(client, userdata, msg):
    print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")


if __name__ == '__main__':
    client = connect_mqtt()
    client.loop_start()
    time.sleep(1)

    battery_num = 16

    json_cabinet = {
        '电池柜编号': '123456',
        '水位报警': 1,
        '火灾报警': 0,
        'GSM信号强度': 123456.12345,
        '电池柜所在的经度': 34.12345,
        '电池柜所在的纬度': 108.12345,
        'arr': []
    }

    json_battery = {
        '电池的充电状态': 1,
        '电池的充电电压': 0.1,
        '电池的充电电流': 0.1,
        '电池的充电机状态': 0,
        '电池编号': 'b001',
        '柜门内电池类型': 0,
        '柜门状态': 0,
        '柜仓温度': 20,
        '电池剩余电量所占的百分比': 98,
        '电池的剩余容量': 98,
        '电池的电压': 0.1,
        '电池的电芯温度': 24,
        '电池所在的经度': 108.12345,
        '电池所在的纬度': 34.12345
    }
    payload = json_cabinet
    for i in range(battery_num):
        j = copy.deepcopy(json_battery)
        j['电池编号'] = f'BB{i}'
        payload['arr'].append(j)

    client.publish("cabinet/state", json.dumps(payload))
    print('send')
    client.disconnect()
